package com.example.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.example.common.to.SkuHasStockVo;
import com.example.gulimall.product.feign.SearchFeignService;
import com.example.gulimall.product.feign.WareFeignService;
import com.google.common.collect.Lists;

import com.example.common.constant.CommonConstant;
import com.example.common.constant.ProductConstant;
import com.example.common.to.SkuReductionTo;
import com.example.common.to.SpuBoundTo;
import com.example.common.to.es.SkuEsModel;
import com.example.common.utils.R;
import com.example.gulimall.product.entity.*;
import com.example.gulimall.product.feign.CouponFeignService;
import com.example.gulimall.product.service.*;
import com.example.gulimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {


    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * SPU检索
     *
     * @param params
     * @return com.example.common.utils.PageUtils
     * @author GuLin
     * @date 15:59 2021/6/8
     **/
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        //检索关键字
        String key = (String) params.get("key");
        //三级分类id
        String catelogId = (String) params.get("catelogId");
        //品牌id
        String brandId = (String) params.get("brandId");
        //商品状态
        String status = (String) params.get("status");
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(item -> {
                item.eq("id", key).or().like("spu_name", key);
            });
        }
        if (StringUtils.isNotBlank(catelogId) && !CommonConstant.NUMBER_0.equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        if (StringUtils.isNotBlank(brandId) && !CommonConstant.NUMBER_0.equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        if (StringUtils.isNotBlank(status)) {
            wrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 保存SPU+SKU货品信息
     *
     * @param vo
     * @return void
     * @author GuLin
     * @date 19:46 2021/6/8
     **/
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(item.getAttrId());
            AttrEntity attrEntity = attrService.getById(item.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(item.getAttrValues());
            valueEntity.setQuickShow(item.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        //6、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        //5、保存当前spu对应的所有sku信息；

        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                //    private String skuName;
                //    private BigDecimal price;
                //    private String skuTitle;
                //    private String skuSubtitle;
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2）、sku的图片信息；pms_sku_image
                skuImagesService.saveBatch(imagesEntities);


                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    /**
     * 商品上架
     *
     * @param spuId
     * @return void
     * @author GuLin
     * @date 16:35 2021/6/9
     **/
    @Override
    public void updatePublishStatus(Long spuId) {
        // 1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkusBySpuId(spuId);
        //2、查出当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> attrValueEntityList = productAttrValueService.baseAttrlistforspu(spuId);
        //获取属性ID集合和SkuID集合
        List<Long> attIds = attrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> skuIds = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查询基本属性ID
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        //属性赋值操作&使用过滤判断是否和idSet匹配
        List<SkuEsModel.Attrs> attrsList = attrValueEntityList.stream()
                .filter(attr -> idSet.contains(attr.getAttrId()))
                .map(attr -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    //数据源-新对象
                    BeanUtils.copyProperties(attr, attrs);
                    return attrs;
                }).collect(Collectors.toList());
        // TODO 3、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            //List<SkuHasStockVo> skuHasStocks = wareFeignService.getSkuHasStocks(longList);
            //stockMap = skuHasStocks.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));

//            R<List<SkuHasStockVo>> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
//            stockMap = skuHasStock.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            //逆转，是一个受保护的方法
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }
        //4、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntityList.stream().map(sku -> {
            //设置需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
//            skuEsModel.setSkuId(0L);
//            skuEsModel.setSpuId(0L);
//            skuEsModel.setSkuTitle("");
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
//            skuEsModel.setSaleCount(0L);
            skuEsModel.setHasStock(null == finalStockMap ? true : finalStockMap.get(sku.getSkuId()));
            skuEsModel.setHotScore(0L);
            //查询品牌信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandId(brandEntity.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            //查询分类
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogId(categoryEntity.getCatId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //检索属性
            skuEsModel.setAttrs(attrsList);
            //复制其他属性
            BeanUtils.copyProperties(sku, skuEsModel);
            return skuEsModel;
        }).collect(Collectors.toList());

        // TODO 5、发送远程调用,将数据发给es进行保存：mall-search
        R r = searchFeignService.productStatusUp(skuEsModelList);
        if (r.getCode() == 0) {
            // 6.远程调用成功,修改当前spu的状态
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            spuInfoEntity.setPublishStatus(ProductConstant.SpuInfoEnum.UP.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            spuInfoEntity.setId(spuId);
            this.updateById(spuInfoEntity);
        } else {
            //7.远程调用失败,重复调用？接口幂等性:重试机制
            /**
             * feign 调用流程
             * 1、构造请求数据，将对象转换为json
             *   RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2.发送请求进行执行（执行成功会解码响应数据信息）
             * 3.执行请求会有重试机制
             *   public Object invoke(Object[] argv) throws Throwable {
             *     // 传过来的数据，构造 RequestTemplate，里面body有数据
             *     RequestTemplate template = buildTemplateFromArgs.create(argv);
             *      // 重试器，要注意重复调用、接口幂等性。可以写重试器自己的实现
             *     Retryer retryer = this.retryer.clone();
             *     while (true) {
             *       try {
             *         // 执行后得到响应，解码得到bean
             *         return executeAndDecode(template);
             *       } catch (RetryableException e) {
             *         try {
             *           retryer.continueOrPropagate(e);
             *         } catch (RetryableException th) {
             *           Throwable cause = th.getCause();
             *           if (propagationPolicy == UNWRAP && cause != null) {
             *             throw cause;
             *           } else {
             *             throw th;
             *           }
             *         }
             *         if (logLevel != Logger.Level.NONE) {
             *           logger.logRetry(metadata.configKey(), logLevel);
             *         }
             *         continue;
             *       }
             *     }
             *   }
             */
        }
    }
}